package com.tyust.service;

import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tyust.dao.CarDao;
import com.tyust.entity.Car;
import com.tyust.pager.PageBean;
import com.tyust.pager.PageConstant;
@Service("carService")
public class CarServiceImpl implements CarService {

	@Autowired
	private CarDao carDao;
	int ps = PageConstant.CAR_PAGE_SIZE;

	@Override
	public Car load(String carNo) {
		try {
			return carDao.findByNo(carNo);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	@Override
	public void addCar(Car car) {
		try {
			carDao.add(car);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void edit(Car car) {
		try {
			carDao.edit(car);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void delete(String carNo) {
		try {
			carDao.delete(carNo);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	@Override
	public PageBean<Car> findByCondition(Car criteria, int pc) {
		List<Car> carList;
		try {
			criteria.setPs(ps);
			criteria.setStart(getStart(pc));
			carList = carDao.findByCondition(criteria);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		return toPageBean(carList, pc,criteria);
	}
	private PageBean<Car> toPageBean(List<Car> list,int pc,Car car){
		Integer tr=0;
		try {
			tr = carDao.findCarCount(car);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		PageBean<Car> pageBean = new PageBean<Car>();
		pageBean.setPc(pc);
		pageBean.setPs(ps);
		pageBean.setTr(tr);
		pageBean.setBeanList(list);
		return pageBean;
	}
	private int getStart(int pc){
		return (pc-1)*ps;
	}
}
